package com.zou.music_downloader.utils;

import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.zou.music_downloader.bean.SongsBean;
import com.zou.music_downloader.sqlite.MyDao;

import java.io.File;


public class FileDownloader {


    public static long download(Context context, Integer fileId, SongsBean bean) {
        String url = bean.getSongurl().getUrl().get(fileId).getFile_link();
        String filename = bean.getSonginfo().getTitle() + "-" + bean.getSonginfo().getAuthor() +
                "-" + bean.getSongurl().getUrl().get(fileId).getFile_bitrate() + "k" +
                "." + bean.getSongurl().getUrl().get(fileId).getFile_extension();

        DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        Log.e("wocao", "download: " + url);

        DownloadManager.Request down = new DownloadManager.Request(Uri.parse(url));
        //设置允许使用的网络类型，移动网络与wifi都可以
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);




/*        File root = new File(Environment.getExternalStorageDirectory() + File.separator + "musicdownloader" + File.separator);
        Uri  path = Uri.withAppendedPath(Uri.fromFile(root), filename);

        down.setDestinationUri(path);*/
        down.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, filename);
        down.allowScanningByMediaScanner();

        long downloadid = dm.enqueue(down);


        Log.e("wocao", "download: " + Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_MUSIC +
                File.separator + filename);
        Log.e("wocao", "download: " + System.currentTimeMillis());

        Log.e("wocao", " " + new File("/storage/emulated/0/Music/我真的受伤了-张学友-24k.mp3").exists());

        MyDao myDao = new MyDao(context);

        myDao.addDate(downloadid
                , bean.getSonginfo().getSong_id()
                , System.currentTimeMillis()
                , Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_MUSIC +
                              File.separator + filename
                , bean.getSonginfo().getTitle()
                , bean.getSonginfo().getAuthor()
                , "已开始"
        );

        return downloadid;
    }


}
